#include "Sprite.h"

Sprite::Sprite(ID3DXSprite *sprite, SpriteData &spriteData, float scale, float lifeTime, bool alphaFade)
{
	mAlphaFade = alphaFade;
	mSprite = sprite;
	mSpriteData = spriteData;
	mScale = scale;
	D3DXCreateTextureFromFileEx(gD3DDevice, mSpriteData.filename, mSpriteData.frameWidth * mSpriteData.numCols, mSpriteData.frameHeight * mSpriteData.numRows, 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), 0, NULL, &mTexture);
	mTimeElapsedSinceLastUpdate = 0.0f;
	mTimeElapsedTotal = 0.0f;
	mCurrentColumn = 1;
	mCurrentRow = 1;
	mLifeTime = lifeTime;
	mCurrentLoop = 0;
	mCenter = D3DXVECTOR3((float)mSpriteData.frameWidth/2, (float)mSpriteData.frameHeight/2, 0.0f);
	mHasStopped = false;
}

Sprite::~Sprite()
{
	mTexture->Release();
}

void Sprite::Update(float dt)
{
	mTimeElapsedSinceLastUpdate += dt;
	mTimeElapsedTotal += dt;

	if (mTimeElapsedSinceLastUpdate < 1 / SPRITEFRAMERATE)
		return;

	if (mTimeElapsedTotal >= mLifeTime)
	//if (mCurrentLoop >= mNumLoops && mNumLoops > 0)
	{
		mHasStopped = true;
		return;
	}

	if (mAlphaFade)
	{
		//mAlpha = (int) ((1 - mTimeElapsedTotal / mLifeTime) * 255);
		float x = mTimeElapsedTotal/mLifeTime;
		mAlpha = (int) ((1 - x*x) * 255);
	}

	mTimeElapsedSinceLastUpdate = 0.0f;
	mCurrentColumn++;

	if (mCurrentColumn % mSpriteData.numCols == 0)
	{
		mCurrentColumn = 1;
		mCurrentRow++;
	}

	if (mCurrentRow > mSpriteData.numRows)
	{
		mCurrentRow = 1;
		mCurrentLoop++;
	}

}

void Sprite::Render(D3DXMATRIX &viewProj, D3DXVECTOR3 &pos, const D3DXMATRIX &rotation)
{
	//if (mCurrentLoop > mNumLoops && mNumLoops > 0)
	if (mTimeElapsedTotal >= mLifeTime)
		return;

	RECT rct;

	rct.left = (mCurrentColumn-1) * mSpriteData.frameWidth;
	rct.right = (mCurrentColumn) * mSpriteData.frameWidth;
	rct.top = (mCurrentRow-1) * mSpriteData.frameHeight;
	rct.bottom = (mCurrentRow) * mSpriteData.frameHeight;

	mSprite->Begin(D3DXSPRITE_OBJECTSPACE | D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_DEPTH_BACKTOFRONT);
	//mSprite->Begin(D3DXSPRITE_ALPHABLEND);
	
	D3DXMATRIX S, T;
	
	D3DXMatrixTranslation(&T, pos.x, pos.y, pos.z);
	D3DXMatrixScaling(&S, mScale, mScale, mScale);
	//D3DXMatrixRotationZ(&R, orientation);

	// Need to rotate it (rotation), scale it (S), then move it into position (T).
	// Finally multiply by the viewProj matrix to render it in world coordinates
	mSprite->SetTransform(&(rotation*S*T*viewProj));
	
	mSprite->Draw(mTexture, &rct, &mCenter, NULL, D3DCOLOR_ARGB(mAlpha, 255, 255, 255));
	mSprite->End();
}

